﻿using PLCSharp.Models;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;

namespace PLCSharp.CoreModel.Prism
{
    public class DialogAwareBase : BindableBase, IDialogAware
    {
        public DialogAwareBase(IContainerExtension container, IEventAggregator ea, IDialogService dialogService)
        {
            _EventAggregator = ea;

        }


        private string _Title = "";
        public string Title
        {
            get { return _Title; }
            set { SetProperty(ref _Title, value); }
        }
        private DelegateCommand<string> _closeDialogCommand;
        public DelegateCommand<string> CloseDialogCommand => _closeDialogCommand ??= new DelegateCommand<string>(CloseDialog);

        private string _message;

        public string Message
        {
            get { return _message; }
            set { SetProperty(ref _message, value); }
        }

        public DialogCloseListener RequestClose { get; }

        protected virtual void CloseDialog(string parameter)
        {
            var resultstr = parameter?.ToLower();
            var result = resultstr switch
            {
                "ok" or "true" => ButtonResult.OK,
                "yes" => ButtonResult.Yes,
                "no" or "false" => ButtonResult.No,
                "cancel" => ButtonResult.Cancel,
                "ignore" => ButtonResult.Ignore,
                _ => ButtonResult.Cancel,
            };
            RaiseRequestClose(new DialogResult(result));
        }

        public virtual void RaiseRequestClose(IDialogResult dialogResult)
        {
            RequestClose.Invoke(dialogResult);
        }

        public virtual bool CanCloseDialog()
        {
            return true;
        }

        public virtual void OnDialogClosed()
        {
        }

        public virtual void OnDialogOpened(IDialogParameters parameters)
        {
            var message = parameters.GetValue<string>("message");
            if (message != null)
            {
                var msg = message.Split(':');

                Title = msg[0];
                if (msg.Length > 1)
                {
                    Message = msg[1];
                }
            }
        }
        protected readonly IEventAggregator _EventAggregator;
        public void SendErr(string msg, ErrType type)
        {
            _EventAggregator.GetEvent<MessageEvent>().Publish(new()
            {
                Type = type,
                Target = "errLog",
                Content = msg
            });
        }
    }
}